package com.mysteel.coupon.service.impl;

import com.mysteel.coupon.entity.SeckillSkuRelationEntity;
import com.mysteel.coupon.service.SeckillSkuRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysteel.common.utils.PageUtils;
import com.mysteel.common.utils.Query;

import com.mysteel.coupon.dao.SeckillSessionDao;
import com.mysteel.coupon.entity.SeckillSessionEntity;
import com.mysteel.coupon.service.SeckillSessionService;
import org.springframework.util.CollectionUtils;


@Service("seckillSessionService")
public class SeckillSessionServiceImpl extends ServiceImpl<SeckillSessionDao, SeckillSessionEntity> implements SeckillSessionService {

    @Autowired
    private SeckillSkuRelationService skuRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SeckillSessionEntity> page = this.page(
                new Query<SeckillSessionEntity>().getPage(params),
                new QueryWrapper<SeckillSessionEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<SeckillSessionEntity> getLatestSession() {
        // 计算最近三天的时间
        String startTime = startTime();
        String endTime = endTime();
        List<SeckillSessionEntity> sessions = this.list(new QueryWrapper<SeckillSessionEntity>().between("start_time", startTime, endTime));
        if (!CollectionUtils.isEmpty(sessions)){
            return sessions.stream().peek(session -> {
                Long sessionId = session.getId();
                List<SeckillSkuRelationEntity> sessionRelationList = skuRelationService.list(new QueryWrapper<SeckillSkuRelationEntity>().eq("promotion_session_id", sessionId));
                session.setRelationSkus(sessionRelationList);
            }).collect(Collectors.toList());
        }
        return new ArrayList<>(0);
    }

    /**
     * 获取秒杀商品上架开始时间
     * @return
     */
    private String startTime(){
        LocalDate now = LocalDate.now();
        LocalTime min = LocalTime.MIN;
        return LocalDateTime.of(now, min).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    /**
     * 获取秒杀商品上架结束时间
     * @return
     */
    private String endTime(){
        LocalDate now = LocalDate.now();
        LocalDate plus = now.plusDays(2);
        LocalTime max = LocalTime.MAX;
        return LocalDateTime.of(plus, max).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

}